﻿#ifndef CLIENT_H
#define CLIENT_H
#include <QObject>
#include <QMutex>
#include <QTcpSocket>
#include "camera.h"
#include <QTimer>


class QTcpSocket;
//和服务器进行数据交换，并将数据传递给相机
class Client : public QObject
{
    Q_OBJECT
public:
    Client(Camera* pc, QObject *parent = nullptr);
    ~Client();
    void InitTimer();
    void CloseSocket();
    void CloseTimer();
    bool Connect(const QString &ip, const quint16 &port, bool &res, int ms_timeout = 1000);
    QList<QByteArray> GetListCommands();
    void SetListCommands(QList<QByteArray> array);

signals:
    void InternalWriteData(const QByteArray &data);
    void sigInitTimer();
    void sigCloseTimer();
    void sigConnect(const QString &ip, const quint16 &port, bool &res, int ms_timeout);
    void sendListAdd(QList<QByteArray>* list);
private:
    void pushDataBuffer(const QByteArray &d);
    void clearBuffer();
    bool checkRecvCommand(const QByteArray &cmd);

    int CameraExternTrigger(quint16 frame, QByteArray data);
    int GetCameraInfo(quint16 frame, QByteArray data);
    int SetCameraMode(quint16 frame, QByteArray data);
    int SetTriggerSource(quint16 frame, QByteArray data);
    int TriggerOne(quint16 frame, QByteArray data);
    int SetExposureTime(quint16 frame, QByteArray data);
    int SetFrame(quint16 frame, QByteArray data);
    int SetAnologGain(quint16 frame, QByteArray data);
    int SetDigiGain(quint16 frame, QByteArray data);
    int SetWindow(quint16 frame, QByteArray data);
    int GetTemp(quint16 frame, QByteArray data);
    int SetpicTMode(quint16 frame, QByteArray data);
    int RecoverCamera(quint16 frame, QByteArray data);
    int SetSaveLocation(quint16 frame, QByteArray data);
    int SetPhotoMessage(quint16 frame, QByteArray data);
    int SendHeartbeat();
    int SendData(const QByteArray& data);
    int SendExternalTriggerNum();
private slots:
    void onScanServer();
    void OnReadData();
    void onCommandParse();
    void onWritData(const QByteArray &data);
//    void onDisconnected(QAbstractSocket::SocketState);
    void onHeartbeat();
    void onInitTimer();
    void onCloseTimer();
    void onConnect(const QString &ip, const quint16 &port, bool &res, int ms_timeout);
    void onGetAndSendPic();
private:
    QTimer *timer = nullptr;
    QTimer *command_timer = nullptr;
    QTimer *heartbeat_timer = nullptr;
    QTimer* external_trigger_success_ = nullptr;
    unsigned int external_trigger_success_timeout_ = 10;
    QTcpSocket* socket = nullptr;
    bool isConnect = false;
    QString serverIp;
    quint16 serverPort = 0;
    int nTimeOut = 500;
    QByteArray lastRemainData;
    QMutex mutex;
    QList<QByteArray> listBuffers;
    Camera* pCamera;
    QList<QByteArray> list;
    int num = 0;
    unsigned char device_num_ = 0x01;
};

#endif // CLIENT_H
